package com.yuns.mas.test.db;

import com.yuns.mas.test.sms.PathUtil;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.*;
import java.util.Properties;

public class DbPlugClient {

	public static void main(String[] args) throws Exception{
		String masJdbcPath = PathUtil.getRootPath()+"../test/db/jdbc.properties";
		InputStream in = new FileInputStream(masJdbcPath);
		Properties props = new Properties();
		props.load(in);

		String db_HostIp = props.getProperty("db_HostIp");
		String db_UserName = props.getProperty("db_UserName");
		String db_Passwd = props.getProperty("db_Passwd");
		System.out.println("本应用程序模拟MAS数据库插件的应用客户端（测试使用）");
		System.out.println("本次被执行的数据库语句：");
		String sqlPath = PathUtil.getRootPath()+"../test/db/sql.txt";
		InputStream fin = new FileInputStream(sqlPath);
		InputStreamReader is = new InputStreamReader(fin);
		BufferedReader br = new BufferedReader(is);
		StringBuffer  buf = new StringBuffer(200000);

		String sql = "";
		while((sql = br.readLine()) != null){
			buf.append(sql);
		}

		System.out.println(buf);
		executeSql(db_HostIp, db_UserName, db_Passwd, buf.toString());
	}

	public static void  executeSql(String db_HostIp, String db_UserName, String db_Passwd, String sql){

		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

		String db_url = "jdbc:mysql://"+db_HostIp+":3306/massi?useUnicode=true&characterEncoding=utf8";
		Connection conn;
		try {
			conn = DriverManager.getConnection(db_url, db_UserName, db_Passwd);
			java.sql.PreparedStatement st = conn.prepareStatement(sql);
			if(sql.startsWith("select")){
				ResultSet rs = st.executeQuery();
				ResultSetMetaData metaDate = rs.getMetaData();
				int count = 0;
				while(rs.next()){
					System.out.println("");
					int cols = metaDate.getColumnCount();
					for (int i = 1; i <= cols; i++) {
						System.out.println(metaDate.getColumnName(i)+": "+rs.getString(i));
					}
					count = count + 1;
				}

				if(count == 0){
					System.out.println("空的查询结果！");
				}
			}
			else{
				st.executeUpdate();

			}
			System.out.println("");
			System.out.println("");
			System.out.println("");
			System.out.println("");
			System.out.println("本次操作执行成功！");
		} catch (SQLException e) {
			System.out.println("");
			System.out.println("");
			System.out.println("");
			System.out.println("");
			System.out.println("本次操作发生异常：");

			if(e.getMessage().indexOf("denied to user") >=0){
				System.out.println("该用户没有执行此操作的权限！");
			}
			else{
				e.printStackTrace();
			}
		}
	}
}
